<template>
  <div class="px-4 sm:px-8 md:px-16 lg:px-48 pt-4 w-full">
    <div class="flex flex-col">
      <n-card :title="'授课计划管理'">
        <template #header-extra>
          <div class="flex items-center">
            <n-button type="primary" @click="openCreateModal" class="px-6 mr-4">
              新增授课计划
            </n-button>
            <n-button type="success" @click="handleExport" :loading="isExporting" class="px-6">
              导出至Excel
            </n-button>
          </div>
        </template>

        <div style="display: flex; flex-wrap: wrap; gap: 16px; margin-top: 16px; margin-bottom: 4px; align-items: center;">
          <div style="flex-shrink: 0; width: 280px;">
            <n-input v-model:value="searchTerm" placeholder="按干部、高校、课程、地点搜索..." clearable @input="handleSearchDebounced"
              @clear="handleSearchDebounced">
              <template #prefix>
                <n-icon :component="SearchOutline" />
              </template>
            </n-input>
          </div>
          <div style="flex-shrink: 0; width: 180px;">
            <n-select v-model:value="filterTeachingStatus" placeholder="选择授课状态" :options="teachingStatusFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex-shrink: 0; width: 180px;">
            <n-select v-model:value="filterSemester" placeholder="选择授课学期" :options="semesterFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex-shrink: 0; width: 180px;">
            <n-select v-model:value="filterCourseSeries" placeholder="选择课程系列" :options="courseSeriesFilterOptions" multiple
              filterable clearable @update:value="applyTableFilters" />
          </div>
          <div style="flex: 1;" />
        </div>

        <div style="margin-top: 0;">
          <n-data-table
            ref="dataTableInstRef"
            :columns="columns"
            :data="planStore.allPlans"
            :loading="planStore.loading"
            :pagination="paginationConfig"
            remote
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
            @update:sorter="handleSorterChange"
            class="min-w-full"
            :scroll-x="2800"
          />
        </div>
      </n-card>
    </div>

    <n-modal
      v-model:show="showModal"
      preset="card"
      :style="{ width: '900px' }"
      :title="modalTitle"
      size="huge"
      :bordered="false"
      :segmented="{ content: 'soft', footer: 'soft' }"
      closable
      @after-leave="handleModalClose"
    >
      <plan-form
        ref="planFormRef"
        :initial-data="editingPlan"
        @submit="handleFormSubmit"
        @cancel="closeModal"
      />
    </n-modal>

    <!-- 干部详情预览模态框 -->
    <n-modal
      v-model:show="showCadreModal"
      preset="card"
      :style="{ width: '900px' }"
      title="干部详细信息"
      size="huge"
      :bordered="false"
      closable
    >
      <div v-if="selectedCadre" class="space-y-6">
        <!-- 基本信息 -->
        <div>
          <h4 class="text-lg font-semibold mb-3 text-gray-700">基本信息</h4>
          <n-descriptions :column="2" bordered>
            <n-descriptions-item label="姓名">{{ selectedCadre.name || '未填写' }}</n-descriptions-item>
            <n-descriptions-item label="性别">{{ selectedCadre.gender || '未填写' }}</n-descriptions-item>
            <n-descriptions-item label="出生年月">{{ formatBirthDate(selectedCadre.birthDate) }}</n-descriptions-item>
            <n-descriptions-item label="籍贯">{{ selectedCadre.nativePlace || '未填写' }}</n-descriptions-item>
            <n-descriptions-item label="级别">{{ selectedCadre.level || '未填写' }}</n-descriptions-item>
            <n-descriptions-item label="职务">{{ selectedCadre.position || '未填写' }}</n-descriptions-item>
            <n-descriptions-item label="干部类型">{{ selectedCadre.cadreType || '未填写' }}</n-descriptions-item>
            <n-descriptions-item label="所属单位">{{ getUnitName(selectedCadre.unitId) }}</n-descriptions-item>
          </n-descriptions>
        </div>

        <!-- 教育背景 -->
        <div>
          <h4 class="text-lg font-semibold mb-3 text-gray-700">教育背景</h4>
          <n-descriptions :column="2" bordered>
            <n-descriptions-item label="最高学历">{{ selectedCadre.highestEducation || '未填写' }}</n-descriptions-item>
            <n-descriptions-item label="最高学位">{{ selectedCadre.highestDegree || '未填写' }}</n-descriptions-item>
          </n-descriptions>
        </div>

        <!-- 专业信息 -->
        <div>
          <h4 class="text-lg font-semibold mb-3 text-gray-700">专业信息</h4>
          <n-descriptions :column="1" bordered>
            <n-descriptions-item label="熟悉专长">
              <div class="whitespace-pre-wrap">{{ selectedCadre.expertise || '未填写' }}</div>
            </n-descriptions-item>
          </n-descriptions>
        </div>

        <!-- 拟授课方向 -->
        <div v-if="selectedCadre.proposedTeachingDirections && selectedCadre.proposedTeachingDirections.length > 0">
          <h4 class="text-lg font-semibold mb-3 text-gray-700">拟授课方向</h4>
          <div class="flex flex-wrap gap-2">
            <n-tag v-for="direction in selectedCadre.proposedTeachingDirections" :key="direction" type="info" size="medium">
              {{ getTeachingDirectionLabel(direction) }}
            </n-tag>
          </div>
        </div>

        <!-- 意向高校 -->
        <div v-if="selectedCadre.intendedUniversity1 || selectedCadre.intendedUniversity2 || selectedCadre.intendedUniversity3">
          <h4 class="text-lg font-semibold mb-3 text-gray-700">意向高校</h4>
          <n-descriptions :column="1" bordered>
            <n-descriptions-item v-if="selectedCadre.intendedUniversity1" label="第一意向">
              {{ getUniversityName(selectedCadre.intendedUniversity1) }}
            </n-descriptions-item>
            <n-descriptions-item v-if="selectedCadre.intendedUniversity2" label="第二意向">
              {{ getUniversityName(selectedCadre.intendedUniversity2) }}
            </n-descriptions-item>
            <n-descriptions-item v-if="selectedCadre.intendedUniversity3" label="第三意向">
              {{ getUniversityName(selectedCadre.intendedUniversity3) }}
            </n-descriptions-item>
          </n-descriptions>
        </div>

        <!-- 其他信息 -->
        <div v-if="selectedCadre.personnelChanges || selectedCadre.remarks">
          <h4 class="text-lg font-semibold mb-3 text-gray-700">其他信息</h4>
          <n-descriptions :column="1" bordered>
            <n-descriptions-item v-if="selectedCadre.personnelChanges" label="人事变动">
              <div class="whitespace-pre-wrap">{{ selectedCadre.personnelChanges }}</div>
            </n-descriptions-item>
            <n-descriptions-item v-if="selectedCadre.remarks" label="备注">
              <div class="whitespace-pre-wrap">{{ selectedCadre.remarks }}</div>
            </n-descriptions-item>
          </n-descriptions>
        </div>

        <!-- 系统信息 -->
        <div v-if="selectedCadre.createdAt || selectedCadre.updatedAt">
          <h4 class="text-lg font-semibold mb-3 text-gray-700">系统信息</h4>
          <n-descriptions :column="2" bordered>
            <n-descriptions-item v-if="selectedCadre.createdAt" label="创建时间">
              {{ formatDateTime(selectedCadre.createdAt) }}
            </n-descriptions-item>
            <n-descriptions-item v-if="selectedCadre.updatedAt" label="更新时间">
              {{ formatDateTime(selectedCadre.updatedAt) }}
            </n-descriptions-item>
          </n-descriptions>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup>
import { SearchOutline } from "@vicons/ionicons5";
import { h, ref, onMounted, computed } from "vue";
import {
  NIcon,
  NDataTable,
  NButton,
  useMessage,
  NInput,
  NSelect,
  NModal,
  NEllipsis,
  NCard,
  useDialog,
  NTag,
  NDescriptions,
  NDescriptionsItem,
} from "naive-ui";
import PlanForm from '@/components/PlanForm.vue';

import { usePlanStore } from '@/stores/planStore';
import { useCadreStore } from '@/stores/cadreStore';
import { useUniversityStore } from '@/stores/universityStore';
import { useUnitStore } from '@/stores/unitStore';
import { teachingStatusOptions, semesterOptions, courseSeriesOptions } from '@/utils/planOptions';
import { teachingDirectionOptions } from '@/utils/cadreOptions';

const message = useMessage();
const dialog = useDialog();
const planStore = usePlanStore();
const cadreStore = useCadreStore();
const universityStore = useUniversityStore();
const unitStore = useUnitStore();

const dataTableInstRef = ref(null);

// --- Modal control for PlanForm ---
const showModal = ref(false);
const modalTitle = ref('新增授课计划');
const editingPlan = ref(null);
const planFormRef = ref(null);

// --- Cadre detail modal ---
const showCadreModal = ref(false);
const selectedCadre = ref(null);

const openCreateModal = () => {
  editingPlan.value = null;
  modalTitle.value = '新增授课计划';
  showModal.value = true;
};

const openEditModal = (rowData) => {
  // 处理嵌套的数据结构，将对象转换为ID
  const planData = {
    ...rowData,
    cadreId: getCadreId(rowData.cadreId),
    universityId: getUniversityId(rowData.universityId)
  };
  editingPlan.value = planData;
  modalTitle.value = '编辑授课计划';
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
};

const handleModalClose = () => {
  if (planFormRef.value && typeof planFormRef.value.resetForm === 'function') {
    planFormRef.value.resetForm();
  }
  editingPlan.value = null;
};

const handleFormSubmit = async (formData) => {
  // 立即关闭对话框，提升用户体验
  closeModal();

  try {
    if (editingPlan.value && editingPlan.value._id) {
      await planStore.updatePlan(editingPlan.value._id, formData);
      message.success('授课计划更新成功');
    } else {
      await planStore.addPlan(formData);
      message.success('授课计划新增成功');
    }

    // 重新获取当前页数据
    await fetchPlansWithFilters();
  } catch (error) {
    console.error("表单提交失败:", error);
    message.error(editingPlan.value ? '更新失败，请重试' : '新增失败，请重试');
    // 不需要重新抛出错误，因为对话框已经关闭了
  }
};

// --- Data Mapping for Display ---
const cadreMap = computed(() => Object.fromEntries(cadreStore.allCadres.map(c => [c._id, c])));
const universityMap = computed(() => Object.fromEntries(universityStore.allUniversities.map(u => [u._id, u])));
const unitMap = computed(() => Object.fromEntries(unitStore.allUnits.map(u => [u._id, u])));
const teachingStatusMap = Object.fromEntries(teachingStatusOptions.map(opt => [opt.value, opt.label]));
const semesterMap = Object.fromEntries(semesterOptions.map(opt => [opt.value, opt.label]));
const courseSeriesMap = Object.fromEntries(courseSeriesOptions.map(opt => [opt.value, opt.label]));
const teachingDirectionMap = Object.fromEntries(teachingDirectionOptions.map(opt => [opt.value, opt.label]));

const getDisplayValue = (value, map, defaultValue = '未知') => map[value] || value || defaultValue;

// 处理嵌套的数据结构
const getCadreName = (cadreData) => {
  if (typeof cadreData === 'object' && cadreData !== null) {
    return cadreData.name || '未知干部';
  }
  return cadreMap.value[cadreData]?.name || '未知干部';
};

const getUniversityName = (universityData) => {
  if (typeof universityData === 'object' && universityData !== null) {
    return universityData.schoolName || '未知高校';
  }
  return universityMap.value[universityData]?.schoolName || '未知高校';
};

const getUnitName = (unitData) => {
  if (typeof unitData === 'object' && unitData !== null) {
    return unitData.name || '未知单位';
  }
  return unitMap.value[unitData]?.name || '未知单位';
};

const getTeachingDirectionLabel = (direction) => teachingDirectionMap[direction] || direction;

// 格式化出生日期
const formatBirthDate = (birthDate) => {
  if (!birthDate) return '未填写';
  try {
    const date = new Date(birthDate);
    if (isNaN(date.getTime())) return '未填写';
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long'
    });
  } catch (error) {
    return '未填写';
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未知';
  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return '未知';
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return '未知';
  }
};

// 获取干部ID（用于编辑和查看详情）
const getCadreId = (cadreData) => {
  if (typeof cadreData === 'object' && cadreData !== null) {
    return cadreData._id || cadreData.id;
  }
  return cadreData;
};

// 获取高校ID（用于编辑）
const getUniversityId = (universityData) => {
  if (typeof universityData === 'object' && universityData !== null) {
    return universityData._id || universityData.id;
  }
  return universityData;
};

// 获取干部对象（用于详情显示）
const getCadreObject = (cadreData) => {
  if (typeof cadreData === 'object' && cadreData !== null) {
    return cadreData;
  }
  return cadreMap.value[cadreData] || null;
};

// Options for filters
const teachingStatusFilterOptions = ref(teachingStatusOptions);
const semesterFilterOptions = ref(semesterOptions);
const courseSeriesFilterOptions = ref(courseSeriesOptions);



const createColumns = ({ onEdit, onDelete, onViewCadre }) => {
  return [
    {
      title: '序号',
      key: 'tableId',
      width: 60,
      fixed: 'left',
      render: (_, index) => (paginationConfig.value.page - 1) * paginationConfig.value.pageSize + index + 1
    },
    {
      title: '授课干部',
      key: 'cadreId',
      width: 120,
      fixed: 'left',
      sorter: true,
      ellipsis: { tooltip: true },
      render: (row) => getCadreName(row.cadreId)
    },
    {
      title: '授课高校',
      key: 'universityId',
      width: 180,
      sorter: true,
      ellipsis: { tooltip: true },
      render: (row) => getUniversityName(row.universityId)
    },
    {
      title: '课程系列',
      key: 'courseSeries',
      width: 150,
      sorter: true,
      render: (row) => getDisplayValue(row.courseSeries, courseSeriesMap)
    },
    {
      title: '课程名称',
      key: 'courseName',
      width: 200,
      sorter: true,
      render: row => h(NEllipsis, { tooltip: { style: { maxWidth: '300px' } } }, { default: () => row.courseName || 'N/A' })
    },
    {
      title: '授课日期',
      key: 'classDate',
      width: 120,
      sorter: true,
      render: (row) => row.classDate ? new Date(row.classDate).toLocaleDateString() : '待定'
    },
    {
      title: '授课时间',
      key: 'classTime',
      width: 120,
      render: (row) => row.classTime || '待定'
    },
    {
      title: '授课地点',
      key: 'location',
      width: 150,
      ellipsis: { tooltip: true },
      render: (row) => row.location || '待定'
    },
    {
      title: '学时',
      key: 'plannedHours',
      width: 80,
      sorter: true,
      align: 'center',
      render: (row) => row.plannedHours ? `${row.plannedHours}h` : '-'
    },
    {
      title: '授课学期',
      key: 'teachingSemester',
      width: 150,
      sorter: true,
      render: (row) => getDisplayValue(row.teachingSemester, semesterMap)
    },
    {
      title: '授课状态',
      key: 'teachingStatus',
      width: 110,
      sorter: true,
      align: 'center',
      render(row) {
        const statusInfo = teachingStatusOptions.find(opt => opt.value === row.teachingStatus);
        return h(NTag, {
          type: statusInfo?.type || 'default',
          bordered: false,
          size: 'small'
        }, {
          default: () => statusInfo?.label || row.teachingStatus
        });
      }
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render(row) {
        return h('div', { style: 'display: flex; align-items: center; justify-content: center;' }, [
          h(NButton, {
            size: 'small',
            type: 'primary',
            ghost: true,
            onClick: () => onEdit(row),
            style: 'margin-right: 8px;'
          }, { default: () => '编辑' }),
          h(NButton, {
            size: 'small',
            type: 'info',
            ghost: true,
            onClick: () => onViewCadre(row.cadreId),
            style: 'margin-right: 8px;'
          }, { default: () => '干部' }),
          h(NButton, {
            size: 'small',
            type: 'error',
            ghost: true,
            onClick: () => onDelete(row)
          }, { default: () => '删除' })
        ]);
      },
    },
  ];
};

const handleViewCadre = (cadreData) => {
  let cadre = null;

  // 如果传入的是对象，直接使用
  if (typeof cadreData === 'object' && cadreData !== null) {
    cadre = cadreData;
  } else {
    // 如果传入的是ID，从store中查找
    cadre = cadreMap.value[cadreData];
  }

  if (cadre) {
    selectedCadre.value = cadre;
    showCadreModal.value = true;
  } else {
    message.warning('未找到该干部信息');
  }
};

const handleDelete = (rowData) => {
  dialog.warning({
    title: '确认删除',
    content: `您确定要删除 "${getCadreName(rowData.cadreId)}" 的授课计划 "${rowData.courseName}" 吗？此操作不可恢复。`,
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: () => {
      // 立即关闭对话框，异步执行删除操作
      performDelete(rowData);
      return true; // 立即关闭对话框
    }
  });
};

const performDelete = async (rowData) => {
  const loadingMessage = message.loading(`正在删除授课计划 "${rowData.courseName}"...`, { duration: 0 });
  try {
    await planStore.deletePlan(rowData._id);
    loadingMessage.destroy();
    message.success(`授课计划已删除`);
    // 重新获取当前页数据
    await fetchPlansWithFilters();
  } catch (error) {
    loadingMessage.destroy();
    message.error('删除失败，请重试');
    console.error("删除失败:", error);
  }
};

const columns = ref(createColumns({
  onEdit: openEditModal,
  onDelete: handleDelete,
  onViewCadre: handleViewCadre,
}));

// --- Data Fetching, Filtering, Pagination, Sorting ---
const searchTerm = ref('');
const filterTeachingStatus = ref([]);
const filterSemester = ref([]);
const filterCourseSeries = ref([]);

const paginationConfig = computed(() => ({
  page: planStore.pagination.page,
  pageSize: planStore.pagination.limit,
  itemCount: planStore.pagination.total,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  showQuickJumper: true,
}));

const currentSortKey = ref(null);
const currentSortOrder = ref(false);
const isExporting = ref(false);



let searchDebounceTimer = null;
const handleSearchDebounced = () => {
    clearTimeout(searchDebounceTimer);
    searchDebounceTimer = setTimeout(() => {
        handleSearch();
    }, 300);
};

const handleSearch = async () => {
  await fetchPlansWithFilters({ page: 1 });
};

// 获取带过滤条件的授课计划数据
const fetchPlansWithFilters = async (paginationParams = {}) => {
  try {
    const params = {
      page: paginationParams.page || planStore.pagination.page,
      pageSize: paginationParams.pageSize || planStore.pagination.limit,
      search: searchTerm.value,
      teachingStatus: filterTeachingStatus.value?.length > 0 ? filterTeachingStatus.value.join(',') : undefined,
      semester: filterSemester.value?.length > 0 ? filterSemester.value.join(',') : undefined,
      sortBy: currentSortKey.value,
      sortOrder: currentSortOrder.value === 'ascend' ? 'asc' : currentSortOrder.value === 'descend' ? 'desc' : undefined,
    };

    // 移除undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key];
      }
    });

    await planStore.fetchPlans(params);
  } catch (error) {
    console.error('获取授课计划数据失败:', error);
    message.error('获取数据失败');
  }
};

const applyTableFilters = async () => {
  await fetchPlansWithFilters({ page: 1 });
};

const handlePageChange = async (page) => {
  await fetchPlansWithFilters({ page });
};

const handlePageSizeChange = async (pageSize) => {
  await fetchPlansWithFilters({ page: 1, pageSize });
};

const handleSorterChange = async (sorter) => {
  if (sorter && sorter.columnKey && sorter.order) {
    currentSortKey.value = sorter.columnKey;
    currentSortOrder.value = sorter.order;
  } else {
    currentSortKey.value = null;
    currentSortOrder.value = false;
  }
  await fetchPlansWithFilters({ page: 1 });
};

// 导出功能
const handleExport = async () => {
  if (isExporting.value) return;

  try {
    isExporting.value = true;

    // 使用简单的 window.open 方式
    const exportUrl = 'http://localhost:3001/api/export/plans';
    window.open(exportUrl, '_blank');

    message.success('授课计划导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败，请重试');
  } finally {
    isExporting.value = false;
  }
};

onMounted(async () => {
  try {
    // 并行加载选项数据
    await Promise.all([
      cadreStore.allCadres.length === 0 ? cadreStore.fetchCadres() : Promise.resolve(),
      universityStore.allUniversities.length === 0 ? universityStore.fetchUniversities() : Promise.resolve(),
      unitStore.allUnits.length === 0 ? unitStore.fetchUnits() : Promise.resolve()
    ]);
    // 加载第一页授课计划数据
    await fetchPlansWithFilters();
  } catch (error) {
    console.error("Error during initial data fetch:", error);
    message.error("初始化数据加载失败");
  }
});
</script>
